package org.zjt.servlet3;

import ma.glasnost.orika.BoundMapperFacade;
import ma.glasnost.orika.MapperFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.zjt.domain.Person;
import org.zjt.domain.PersonDto;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;
import java.util.Arrays;
import java.util.Date;

/**
 * DESC
 *
 * @author
 * @create 2017-07-17 下午4:14
 **/

@WebServlet(name = "myServlet", urlPatterns = "/myServlet", description = "servlet 3.0测试", initParams = {@WebInitParam(name = "author", value = "zhangJuntao")})
public class MyServlet extends HttpServlet {

    @Autowired
    private MapperFactory beanMapperFactory;

    private String author;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getParameterMap().forEach((k, v) -> getServletContext().log(k + "  " + String.valueOf(Arrays.stream(v).reduce(new String(), (a, b) -> b + "," + a, (a, b) -> b + a))));
        Writer writer = resp.getWriter();

        ServletContext servletContext = getServletContext();

        servletContext.log("myServlet doGet ...");

        BoundMapperFacade<PersonDto, Person> mapperFacade = beanMapperFactory.getMapperFacade(PersonDto.class, Person.class);
        PersonDto personDTO = new PersonDto("zhang","juntao",new Date(),new String[][]{ {"1","2"}, {"4","5"} });
        Person map = mapperFacade.map(personDTO);
        servletContext.log(map.getName().toString());

        req.getSession().setAttribute("userId", 111);
        writer.write("<html><body>Hello,World , my value = " + author + " </body></html>");
    }


    @Override
    public void destroy() {
        super.destroy();
        getServletContext().log("--------servlet destroy--------------");
    }

    @Override
    public void init() throws ServletException {
        super.init();
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        author = config.getInitParameter("author");
        getServletContext().log("--------servlet init--------------");
    }
}
